import tkinter as tk
from tkinter import messagebox
import numpy as np
from matplotlib import pyplot as plt


def draw_bar_chart(window):
    window.withdraw()  # 隐藏当前窗口
    draw_bar_window = tk.Toplevel()  # 创建新窗口
    draw_bar_window.title("绘制柱状图")  # 界面标题
    draw_bar_window.geometry("400x300")  # 窗口大小

    # 用户输入数据
    tk.Label(draw_bar_window, text="输入类别，用逗号分隔:").pack()
    category_entry = tk.Entry(draw_bar_window)
    category_entry.pack()
    tk.Label(draw_bar_window, text="输入数值，用逗号分隔:").pack()
    value_entry = tk.Entry(draw_bar_window)
    value_entry.pack()

    # 绘制按钮
    def draw():
        try:
            # 字符串分割，然后读取并转化成float类型存进数组
            categories = category_entry.get().split(',')
            values = np.array([float(i) for i in value_entry.get().split(',')])

            if len(categories) != len(values):
                messagebox.showerror("错误", "类别和数值的数量必须相同")
                return

            # 绘制柱状图
            plt.bar(categories, values, color=(0.678, 0.847, 0.902))
            plt.xlabel('类别')
            plt.ylabel('数值')
            plt.title('柱状图')
            plt.show()
        except ValueError:
            messagebox.showerror("错误", "请输入有效的数值")

    draw_button = tk.Button(draw_bar_window, text="绘制柱状图", command=draw)
    draw_button.pack()

    return_button = tk.Button(draw_bar_window, text="返回",
                              command=lambda: [draw_bar_window.destroy(), window.deiconify()])
    return_button.pack()
